import numpy as np
from PIL import Image
import ctypes
import cv2
import os

label_path = "C:\\Users\\jiangshan\\Desktop\\ref_label.txt"
label_list = np.loadtxt(label_path, dtype=np.str)
print(label_list)

file_dir = "C:\\Users\\jiangshan\\Desktop\\color"
img_list = []
for root, dirs, files in os.walk(file_dir):
    if files:
        for file in files:
            img_path = root
            img_list.append(root + "\\" + file)
            img_path = img_path.replace("color", "calibrate")
            # print(img_path)
            # print(os.path.exists(img_path))
            if not os.path.exists(img_path):
                os.makedirs(img_path)


mapping_matrix = np.array([[2.83269438e+00, -5.68796925e-03, 1.73472348e-18],
                           [-9.28598668e-03, 2.94509748e+00, -1.73472348e-18],
                           [3.33378047e+02, -9.36243388e+01, 1.00000000e+00]])

for color_image_name in img_list:
    color_image = np.array(Image.open(color_image_name))
    mapped_color_image = np.zeros((424, 512, 3), dtype='uint8')
    for i in range(424):
        for j in range(512):
            coordinate = np.dot(np.array([j, i, 1]), mapping_matrix)
            # print(coordinate.shape)
            color_x = coordinate[0]
            color_y = coordinate[1]
            if not (color_x == '-inf' or color_y == '-inf'):
                color_x = int(round(float(color_x)))
                color_y = int(round(float(color_y)))
                if 0 <= color_x < 1920 and 0 <= color_y < 1080:
                    mapped_color_image[i][j][0] = int(color_image[color_y][color_x][0])
                    mapped_color_image[i][j][1] = int(color_image[color_y][color_x][1])
                    mapped_color_image[i][j][2] = int(color_image[color_y][color_x][2])
    calibrate_image_name = color_image_name.replace("color", "calibrate")
    img = Image.fromarray(mapped_color_image)
    img.save(calibrate_image_name)
